import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:loxen/api/http_server/dictionaries.dart';
import 'package:loxen/api/http_server/file_change_delete_add_select.dart';
import 'package:loxen/dialog/dialog_utils.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/master/master_index_bean.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/master_index_viewmodel.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/mode/master/file_loxen.dart';
import 'package:loxen/routes/routes.dart';

class MasterFileList extends StatelessWidget with FileChangeDeleteAddSelectMixin {
  final FileShow data;
  final bool isMe;
  final String userId;

  const MasterFileList({Key key, this.data, this.isMe = true, this.userId}) : super(key: key);

  // 编辑
  void changeName(BuildContext contextMain, _ItemViewModel viewModel, FileLoxen file) {
    showDialog<String>(
      context: contextMain,
      builder: (context) {
        return DialogUtil.getChangeFileNameDialog(context, file, onChange: (select, text) {
          Stream<int> data;
          if (text.trim() != file.name) {
            data = fileChangeName(file.id.toString(), name: text, isHide: select);
          } else {
            data = fileChangeName(file.id.toString(), isHide: select);
          }
          data.listen((event) {
            if (event == 200) {
              file.name = text;
              file.isHide = select;
              viewModel.notifier();
            } else {
              Toast.show("修改失败", contextMain);
            }
          }, onError: (error, stack) {
            Toast.show("网络异常", contextMain);
            print(error);
            print(stack);
          });
        });
      },
    );
  }

  Widget _tabTitle(BuildContext context, String str, FileType type) {
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pushNamed(Routes.master_file_list, arguments: {
          'type': type,
          'userId': userId,
          'isMe': isMe
        }).then((value) => context.read<MasterIndexViewModel>().loadData());
      },
      child: Container(
        margin: EdgeInsets.only(left: 37.w, right: 17.w, top: 40.h),
        height: 45.h,
        decoration: BoxDecoration(
            border: Border(left: BorderSide(color: Theme.of(context).primaryColor, width: 5.w))),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 20.w),
                child: Container(
                  margin: EdgeInsets.only(bottom: 0.h),
                  child: Text(
                    str,
                    style: TextStyle(
                        fontSize: 31.sp,
                        fontWeight: FontWeight.bold,
                        color: Theme.of(context).textTheme.subtitle2.color),
                  ),
                  alignment: Alignment.topLeft,
                ),
              ),
            ),
            Text(
              StringResources.cha_kan_geng_duo,
              style: TextStyle(fontSize: 24.sp, color: Color(0xff999999)),
            ),
            Icon(
              Icons.navigate_next,
              color: Theme.of(context).primaryTextTheme.subtitle1.color,
            )
          ],
        ),
      ),
    );
  }

  Widget _files(BuildContext context, List<FileLoxen> files, String type, FileType fileType) {
    List<Widget> list = files.map((entity) {
      var data = _ItemViewModel(entity);
      return ChangeNotifierProvider.value(
        value: data,
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            GestureDetector(
              onLongPress: () {
                if (isMe && entity.canEdit == 1) {
                  changeName(context, data, entity);
                }
              },
              onTap: () {
                Navigator.of(context).pushNamed(Routes.master_file_info, arguments: {
                  'file': entity,
                  'type': fileType,
                  'isMe': isMe,
                  'userId': userId
                }).then((value) => data.notifier());
              },
              child: Stack(
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    child: ClipRRect(
                        borderRadius: BorderRadius.circular(15.w),
                        child: entity.cover != null && entity.cover != ''
                            ? CachedNetworkImage(
                                imageUrl:  ImageUrlUtil.getClean(entity.cover),
                                placeholder: (_, __) => Constants.loadingIcon(),
                                fit: BoxFit.cover,
                              )
                            : Center(
                                child: Image.asset(
                                  'images/default_folder.png',
                                  width: 57.w,
                                  height: 49.w,
                                ),
                              )),
                    decoration: BoxDecoration(
                        color: Color(0xFF0CB7D9),
                        borderRadius: BorderRadius.all(Radius.circular(15.w))),
                  ),
                  Builder(builder: (context) {
                    bool select = context.select<_ItemViewModel, bool>((value) => entity.isHide);
                    return select
                        ? AbsorbPointer(
                            child: Container(
                              width: double.infinity,
                              height: double.infinity,
                              decoration: BoxDecoration(
                                color: Colors.white.withAlpha(76),
                                borderRadius: BorderRadius.circular(15.w),
                              ),
                              child: Center(
                                child: Image.asset(
                                  'images/icon_privacy.png',
                                  width: 58.w,
                                  height: 58.w,
                                ),
                              ),
                            ),
                          )
                        : Constants.empty;
                  }),
                ],
              ),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                height: 61.h,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Colors.black.withAlpha(76),
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(15.w),
                    bottomRight: Radius.circular(15.w),
                  ),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.only(left: 25.w),
                      child: Builder(builder: (context) {
                        String name = context.watch<_ItemViewModel>().entity.name;
                        return Text(
                          name,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: 20.sp,
                              color: Theme.of(context).textTheme.subtitle1.color,
                              fontWeight: FontWeight.w500),
                        );
                      }),
                    ),
                    Container(
                      padding: EdgeInsets.only(left: 25.w),
                      width: double.infinity,
                      child: Builder(builder: (context) {
                        var num = context.select<_ItemViewModel, int>((value) => value.entity.num);
                        return Text(
                          '$num$type',
                          style: TextStyle(fontSize: 13.sp, color: Colors.white),
                        );
                      }),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    }).toList();
    return Container(
      height: 240.h,
      width: double.infinity,
      child: list != null && list.length > 0
          ? GridView.count(
              crossAxisCount: 1,
              scrollDirection: Axis.horizontal,
              mainAxisSpacing: 20.w,
              childAspectRatio: 1.5,
              children: list,
            )
          : Center(child: Text('暂无公开文件夹')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        _tabTitle(context, StringResources.ling_gan, FileType.INSPIRATION),
        Padding(
          padding: EdgeInsets.only(left: 35.w, top: 24.h),
          child: _files(context, data.article, StringResources.ling_gan, FileType.INSPIRATION),
        ),
        _tabTitle(context, StringResources.su_cai, FileType.MATERIAL),
        Padding(
          padding: EdgeInsets.only(left: 35.w, top: 24.h),
          child: _files(context, data.product, StringResources.su_cai, FileType.MATERIAL),
        ),
        _tabTitle(context, StringResources.cai_ji, FileType.IMAGE),
        Padding(
          padding: EdgeInsets.only(left: 35.w, top: 24.h),
          child: _files(context, data.picture, StringResources.cai_ji, FileType.IMAGE),
        ),
      ],
    );
  }
}

class _ItemViewModel extends ChangeNotifier {
  final FileLoxen entity;

  _ItemViewModel(this.entity);

  void notifier() {
    notifyListeners();
  }
}
